package com.colbert.jknife;

import android.app.Activity;

import com.colbert.jknife.model.Constant;
import com.colbert.jknife.model.IInjectAdapter;

import java.util.LinkedHashMap;
import java.util.Map;

public class JKnife {

    private static Map<Class<?>, IInjectAdapter<?>> sInjectAdapterMap;

    static {
        sInjectAdapterMap = new LinkedHashMap<>();
    }

    public static void inject(Activity activity) {
        try {
            IInjectAdapter<Activity> injectAdapter = getInjectAdapter(activity.getClass());
            injectAdapter.inject(activity, null);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static <T> IInjectAdapter<T> getInjectAdapter(Class<? extends T> clazz) {
        IInjectAdapter<T> injectAdapter = (IInjectAdapter<T>) sInjectAdapterMap.get(clazz);
        if (injectAdapter == null) {
            String adapterClassName = clazz.getName() + Constant.CLASS_SUFFIX;
            try {
                Class<T> adapterClazz = (Class<T>) Class.forName(adapterClassName);
                injectAdapter = (IInjectAdapter<T>) adapterClazz.newInstance();
                sInjectAdapterMap.put(clazz, injectAdapter);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return injectAdapter;
    }
}
